import { ElMessage } from 'element-plus'

interface LoadingConfug {
  /**
   * 超时时间
   */
  timeout?: number
  /**
   * 超时消息提示
   */
  msgTitle?: string
  /**
   * 提示消息类型
   */
  msgType?: 'success' | 'warning' | 'error' | 'info'
}

interface CloseLoading {
  /**
   * 请求状态码
   */
  code: number
  /**
   * 请求成功状态码
   */
  successCode?: number
}

type CloseLoadingFunction = () => void

export function useTable<T>() {
  const pageConfig = reactive({
    total: 100,
    size: 5,
    page: 1,
    list: [] as Array<T>,
  })

  /**
   * 加载动画开关
   */
  const loading = ref(false)

  /**
   * 关闭加载动画
   */
  const closeLoading: CloseLoadingFunction = () => {
    loading.value = false
  }

  type ByCodeCloseLoading = (
    config: CloseLoading,
    successCallback: Function,
    errorCallback?: Function
  ) => void

  /**
   * 通过请求状态码关闭加表格载动画
   * @param config 请求code值配置
   * @param successCallback 成功回调
   * @param errorCallback 失败回调
   */
  const byCodeCloseLoading: ByCodeCloseLoading = (
    config: CloseLoading,
    successCallback: Function,
    errorCallback?: Function
  ) => {
    const defaultConfig: CloseLoading = {
      successCode: 200,
      ...config,
    }
    const { code, successCode } = defaultConfig
    if (code === successCode) {
      loading.value = false
      successCallback()
    } else {
      errorCallback ? errorCallback() : ''
      loading.value = false
      clearTimeout(loadingTime.value)
      ElMessage({
        message: '请求失败',
        type: 'error',
      })
    }
  }

  const loadingTime = ref()
  const openLoading = (config?: LoadingConfug) => {
    const defaultConfig: LoadingConfug = {
      timeout: 3000,
      msgTitle: '加载超时',
      msgType: 'error',
      ...config,
    }

    loading.value = true
    clearTimeout(loadingTime.value)
    loadingTime.value = setTimeout(() => {
      if (loading.value) {
        loading.value = false
        ElMessage({
          message: defaultConfig.msgTitle,
          type: defaultConfig.msgType,
        })
      }
    }, defaultConfig.timeout)
  }

  /**
   * 加载表格数据
   */
  type InitTableDataCallback = (data: {
    closeLoading: CloseLoadingFunction
    byCodeCloseLoading: ByCodeCloseLoading
  }) => void
  const initTableData = (callback: InitTableDataCallback) => {
    return () => {
      openLoading()
      callback({
        //关闭加载动画
        closeLoading,
        byCodeCloseLoading,
      })
    }
  }

  return {
    pageConfig,
    loading,
    openLoading,
    closeLoading,
    byCodeCloseLoading,
    initTableData,
  }
}
